/**
 * 构建一个完整的URL路径
 * @param {string} url 路径
 * @param {Object} params 参数对象
 * @returns 返回完整URL路径
 */
export default function buildURL(url, params) {
    let standardURL = url;
    if (!isAbsoluteURL(url)) {
        standardURL = resolveURL(location.origin, url.replace(/^\//, ''));
    }
    if (params) {
        standardURL += '?' + serializeParams(params);
    }
    return standardURL;
}

/**
 * 序列化参数
 * @param {Object} params 待序列化参数
 * @returns 返回序列化字符串
 */
export function serializeParams(params = {}) {
    const arr = [];
    Object.keys(params).forEach((key) => {
        arr.push(`${key}=${encodeURIComponent(params[key])}`);
    });
    return arr.join('&');
}

/**
 * 拼接多个URL
 * @param  {...any} args 多个URL路径
 * @returns 返回拼接后的URL
 */
export function resolveURL(...args) {
    const url = args.reduce((prev, current = '') => {
        if (current) {
            const next = current.replace('\\', '/');
            return prev ? prev + '/' + next : next;
        }
        return prev;
    }, '');
    return url;
}

/**
 * 判断是否是完整URL
 * @param {string} url 待判断URL
 * @returns 返回是否是完整URL
 */
export function isAbsoluteURL(url) {
    const regex = /^([a-z][a-z\d\+\-\.]*:)?\/\//i;
    return regex.test(url);
}
